package com.wangt.biz.controller;

import com.wangt.biz.socket.TCPCache;
import com.wangt.biz.socket.TCPClient;
import io.netty.channel.ChannelHandlerContext;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 系统作为  socket 服务端
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/socket")
public class SocketController {

    @PostMapping("/send")
    public String send(String host, Integer port, String msg) {
        try {
            TCPClient.sendMsg(host, port, msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 向指定的客户端发送数据
     * @param clientName
     * @param msg
     * @return
     */
    @PostMapping("/toClsend")
    public String send(String clientName, String msg) {
        ChannelHandlerContext context = TCPCache.INSTANCE.getClientInfoContext().get(clientName);
        context.writeAndFlush(msg);
        return "success";
    }

}
